<?php
/**
 * Created by PhpStorm.
 * User: 常志明
 * Date: 2018-08-13
 * Time: 18:46
 * 用户管理 user表
 *
 * -1--->'UserMange'--->用户
 *                      ||
 *                   usermange
 *                  用户信息（client_id,   weixin_id, username, passwd, phone, email, position_id, store_id, img）
 *                           唯一客户端ID   微信ID     用户名    密码    手机   邮箱    职位id       门店id    头像
 *                            string        string     string  string   sring sring   string       string  sring
 */

namespace app\index\controller;

use think\Cookie;
use Aliyun\Core\Config as AliyunConfig;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;

use Yurun\OAuthLogin\Weixin\OAuth2;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class User
{
    const usermange = [
        'client_id'   =>'',     //唯一客户端ID
        'weixin_id' =>'',       //微信ID
        'username'  =>'',       //用户名
        'passwd'=>'',           //密码
        'phone' =>'',           //手机
        'email'  =>'',          //邮箱
        'position_id' =>'',     //职位id  == 专业id
        'store_id'=>'',         //门店id  -->storemanage(id)
        'img'=>'',              //头像
        'rankName'=>'员工',     //用户级别权限
        'datetime'=>'',         //申请时间
        'status'  =>'待审核',    //申请状态
        'desc'    =>'',         //申请描述
    ];
    public static function getData($where, $one = true, $table = 'usermange')
    {
        return ($one == true) ? getFirst(mongo($table)->where($where)->select()) : mongo($table)->where($where)->select();
    }
    public static function setData($where, $data, $table = 'usermange')
    {
        mongo($table)->where($where)->update($data);
    }
    public static function insertData($data, $table = 'usermange')
    {
        mongo($table)->insert($data);
        return mongo($table)->getLastInsID();
    }
    public static function deleteData($where, $table = 'usermange')
    {
        mongo($table)->where($where)->delete();
    }

    /**
     * 注册
     * @param string $userName  用户名
     * @param string $password  密码
     * @param string $code      验证码
     * @param string $phone     手机号
     * @return array
     */
    public static function registerDb($userName = '', $password = '', $code = '', $phone = '', $store ='', $position = '', $desc = '')
    {
        $userName   = input('userName');
        $password   = input('password');
        $code       = input('code');
        $phone      = input('phone');
        $store      = input('store');
        $position   = input('position');
        $desc       = input('desc');

        $data = self::getData(['phone'=>$phone]);
        if(!empty($data)) {
            return RD(FAIL, '用户已经存在');
        }
        if(!empty($phone) && !empty($code) && cookie("phone") == $phone && cookie("verification") == $code) {
            $insertData = [
                'username' => $userName,
                'passwd'   => $password,
                'phone'    => $phone,
                'store_id' => $store,
                'rankName' => $position,
                'datetime' => date('Y-m-d'),
                'desc'     => $desc,
            ];
            self::insertData(array_merge(self::usermange, $insertData));
            self::logout();
            return RD(SUCCESS, $insertData);
        }
        self::logout();
        return ["status"=> 0, "message"=> "验证码错误"];
    }
    /**
     *  登录
     * @param string $username  手机号
     * @param string $passwd    密码
     * @return array
     */
    public static function loginDb($username = null, $passwd = null)
    {
        $username = input("username");
        $passwd   = input('passwd');

        $user = self::getData(['phone'=>$username]);
        if(empty($user)) {
            return RD(FAIL, '用户不存在');
        }
        //登录成功
        if(((!empty($username) && !empty($passwd) && cookie("phone") == $username && cookie("verification") == $passwd)
            || ($username == ($user['phone'] ?? '') && $passwd == ($user['passwd'] ?? '')))) {
            if(($user['status'] ?? '') != '已通过') {
                return RD(FAIL, '审核未通过');
            }
            cookie("phone", $user["phone"], 3600 * 24);      //设置cookie手机号
            $clientId= rand(100000000, 999999999)."";
            cookie("client_id", $clientId, 3600 * 24);        //客户端id
            cookie('userId', $user["id"], 3600 * 24);         //用户ID
            $user['client_id'] = $clientId;

            self::setData(['phone'=>$username], ['client_id'=>$clientId]);  //更新客户端id
            $user['storeName']  = Store::getData(['id'=>$user['store_id']])['storeName'] ?? '';
            return RD(SUCCESS, $user);
        }
        return RD(FAIL, '用户名或密码错误');
    }
    /**
     * 编辑密码
     * @param null $userId  用户id
     * @param null $oldPass 旧密码
     * @param null $newPass 新密码
     * @return array
     */
    public static function editPasswordDb($userId = null, $oldPass = null, $newPass = null)
    {
        if(!empty($perssion = perssion([LOGIN])))
            return $perssion;

        $userId   = input('userId');
        $oldPass  = input('oldPass');
        $newPass  = input('newPass');

        $passwd = self::getData(['id'=>$userId])['passwd'] ?? '';
        if($oldPass == $passwd) {
            self::setData(['id'=>$userId], ['passwd'=>$newPass]);
            return RD(SUCCESS);
        }
        return RD(FAIL, 'id或以前密码错误');
    }

    /**
     * 修改用户名
     * @param string $userId    用户id
     * @param string $userName  用户名
     * @return array
     */
    public static function editUserNameDb($userId = null, $userName = null)
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;

        $userId  = input('userId');
        $userName= input('userName');

        self::setData(['id'=>$userId], ['username'=>$userName]);
        return RD(SUCCESS, $userName);
    }

    /**
     * 修改手机号
     * @param string $userId  用户id
     * @param string $phone   手机号
     * @param string $code    验证码
     * @return array
     */
    public static function editPhoneDb($userId = null, $phone = null, $code = null)
    {
        if(!empty($perssion = perssion([LOGIN])))
            return $perssion;
        $userId  = input('userId');
        $phone   = input('phone');
        $code    = input('code');

        if(!empty($phone) && !empty($code) && cookie("phone") == $phone && cookie("verification") == $code) {
            self::setData(['id'=>$userId], ['phone'=>$phone]);
            return RD(SUCCESS);
        }
        return RD(FAIL, '手机号或验证码错误');
    }

    /**
     * 忘记密码
     * @param string $phone    手机号
     * @param string $code      验证码
     * @param string $password  密码
     * @return array
     */
    public static function forgetPasswdDb($phone = null, $code = null, $password = null)
    {
        $phone    = input('phone');
        $code     = input('code');
        $password = input('password');

        if(!empty($phone) && !empty($code) && cookie("phone") == $phone && cookie("verification") == $code) {
            self::logout();                 //清空
            mongo('usermange')->where(['phone'=>$phone])->update(['passwd'=>$password]);
            return RD(SUCCESS);
        }
        return RD(FAIL, '验证码错误');
    }

    /**
     * 上传头像
     * @param string $userId  用户id
     *        file   $file
     * @return array
     */
    public static function uploadPhotoDb($userId = null, $file = [])
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;
        $userId = input('userId');

        $path = self::getData(['id'=>$userId])['img']??'';
        deleteFileIn($path);      //删除头像
        $path = uploadFileIn();   //获上传路径

        self::setData(['id'=>$userId], ['img'=>$path]);//插入图片路径
        return RD(SUCCESS, $path);
    }
    //
    //获取门店id
    public static function getStoreId()
    {
        return self::getData(['id'=>cookie("userId")])['store_id'] ?? '';
    }
    //退出登录清空CooKie
    public static function logout()
    {
        cookie("phone", NULL);       //手机号
        cookie("client_id", NULL);   //清空客户端id
        cookie('userId', NULL);      //用户id
        return ["status"=> 1, "message"=> "退出登录成功"];
    }
    //判断是否登录
    public static function isLogin()
    {
        cookie("phone", cookie("phone"), 3600 * 24);           //设置cookie手机号
        cookie("client_id", cookie("client_id"), 3600 * 24);   //设置client_id
        cookie("userId", cookie("userId"), 3600 * 24);         //设置userId
        
        $clientId = self::getData(["phone"=>cookie("phone")])['client_id'] ?? '';
        return true;
        return (empty($clientId) || $clientId != cookie('client_id')) ? false : true;
    }
    //微信登录回调
    public static function weiXinSuccess()
    {
        $weixin = new OAuth2('wxb807f61624246d62', 'a479805535cabd3bdac8b5b7dc5443fd', 'http://www.huikezk/api/weiXinSuccess');
        // 获取accessToken
        $accessToken = $weixin->getAccessToken($_SESSION['YURUN_QQ_STATE']);

        // 调用过getAccessToken方法后也可这么获取
        // $accessToken = $qqOAuth->accessToken;
        // 这是getAccessToken的api请求返回结果
         $result = $weixin->result;
        // 用户资料
         $userInfo = $weixin->getUserInfo();
        // 用户唯一标识
        $openid = $weixin->openid;
    }
    //微信登录
    public static function weiXinLogin()
    {
        $weixin = new OAuth2('wxb807f61624246d62', 'a479805535cabd3bdac8b5b7dc5443fd', 'http://www.huikezk/api/weiXinSuccess');

        //$url = $weixin->getWeixinAuthUrl();
        $url = $weixin->getAuthUrl();
        $_SESSION['YURUN_QQ_STATE'] = $weixin->state;
        header('location:' . $url);
    }
    /**
     * post/get 获取验证码
     * @param string phone 手机号
     * @return json {"status":1,"message":"成功","data":{"code":"1234"}}
     */
    public static function getCode()
    {
        //----------------Var----------------------//
        $number = input("phone");

        if(empty($number))
            return RD(FAIL, '手机号不能为空');

        // 阿里云Access Key ID和Access Key Secret 从 https://ak-console.aliyun.com 获取
        $appKey = 'LTAIvvThz1IOKVYq';
        $appSecret = 'I3JwdOhAaHb3Ca2C4J7VFajrGlTGx0';

        // 短信签名 详见：https://dysms.console.aliyun.com/dysms.htm?spm=5176.2020520001.1001.3.psXEEJ#/sign
        $signName  = '北京汇科智控';

        // 短信模板Code https://dysms.console.aliyun.com/dysms.htm?spm=5176.2020520001.1001.3.psXEEJ#/template
        $template_code = 'SMS_142075337';

        // 短信中的替换变量json字符串
        $code = rand(1000, 9999)."";
        $json_string_param =json_encode(["code"=>$code]);

        // 接收短信的手机号码
        $phone = $number;

        // 初始化阿里云config
        AliyunConfig::load();
        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile("cn-hangzhou", $appKey, $appSecret);
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        $acsClient = new DefaultAcsClient($profile);
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);
        // 必填，设置签名名称
        $request->setSignName($signName);
        // 必填，设置模板CODE
        $request->setTemplateCode($template_code);

        // 可选，设置模板参数
        if(!empty($json_string_param)) {
            $request->setTemplateParam($json_string_param);
        }
        // 发起请求
        $acsResponse =  $acsClient->getAcsResponse($request);
        // 默认返回stdClass，通过返回值的Code属性来判断发送成功与否
        if($acsResponse && strtolower($acsResponse->Code) == 'ok')
        {
            $result = ["status"=> 1, "message"=> "成功"];
            cookie("phone", $number, 120);
            cookie("verification", $code, 120);
        }
        else {
            $result = ["status"=> 0, "message"=> "失败"];
        }
        return $result;
    }
    /**
     * 绑定邮箱
     * @param string $userId   用户id
     * @param string $mailAddr 邮箱地址  == '’清空邮箱
     * @param string $code     验证码
     * @return array
     */
    public static function bindEmail($userId = null, $mailAddr = null, $code = null)
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;

        $userId   = input('userId');
        $mailAddr = input('mailAddr');
        $code     = input('code');

        if((empty($mailAddr) && cookie("mailCode") == $code)  || (!empty($mailAddr) && !empty($code) && cookie("mailAddr") == $mailAddr && cookie("mailCode") == $code)) {
            self::setData(['id' =>$userId], ['email'=>$mailAddr]);
            return RD(SUCCESS);
        }
        return RD(FAIL, '验证码不正确');
    }
    /**
     * 获取邮箱验证码
     * @param string $mailAddr  邮箱地址
     * @return array
     */
    public static function getMailCode($mailAddr = null)
    {
        $mailaddr = input("mailAddr");
        if(empty($mailaddr)) {
            return RD(FAIL);
        }

        $code = rand(1000, 9999)."";
        cookie("mailAddr", $mailaddr, 120);
        cookie("mailCode", $code, 120);

        $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
        try {
            //Server settings
            //$mail->SMTPDebug = 2;                                 // Enable verbose debug output
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'smtp.mxhichina.com';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'mail@huikezk.com';                 // SMTP username
            $mail->Password = 'chang123..';                       // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to

            //Recipients
            $mail->setFrom('mail@huikezk.com', '汇科智控');
            $mail->addAddress($mailaddr);     // Add a recipient
            $mail->Subject = '汇科智控用户邮箱验证';
            $mail->Body    = $code;
            $mail->send();
            return RD(SUCCESS, ["code"=>$code]);
        } catch (Exception $e) {
            return RD(FAIL, ["code"=>$mail->ErrorInfo]);
        }
    }

    /**
     * 我的工单
     * @param string $warrantyMaintenance  我的报修或已完成
     * @param string $messageType  维保作业单  日常维修单
     * @param string $keyWord      搜索
     * @param string $datetime
     * @return array
     */
    public static function myRepairOrder($warrantyMaintenance = '', $messageType = '', $datetime = '', $keyWord = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))
            return $perssion;

        $messageType = input('messageType');
        $datetime    = input('datetime');
        $warrantyMaintenance = input('warrantyMaintenance');
        $keyWord     = input('keyWord');

        $data = [];
        if($warrantyMaintenance == '我的报修') {
            switch ($messageType) {
                case '维保作业单':
                    break;
                case "日常维修单":
                    $where = [
                        'people'     => cookie('userId'),
                        'deviceNum'  => ['like', '.*'.$keyWord.'.*'],
                        'datetime'  => ['like', '.*'.$datetime.'.*'],
                    ];
                    $result = Malfunction::getData($where, false);//故障报修单
                    foreach ($result as $malfunction) {
                        array_push($data, [
                            'majorName'   =>'',
                            'deviceNum'   =>'',
                            'deviceKind'  =>'',
                            'receiverName'=>$malfunction['people'],
                            'completeTime'=>$malfunction['datetime']
                        ]);
                    }
                    break;
            }
        }
        if($warrantyMaintenance == '已完成') {
            switch ($messageType) {
                case '维保作业单':
                    $data = [];
                    $jobcard_devices = JobCard::getData(['receiverId'=>cookie('userId'),'completeTime'=>['like', $datetime.'.*']], false);
                    foreach ($jobcard_devices as $key=>$device) {
                        $jobCard  = JobCard::getData(['id'=>$device['parentId']]);
                        array_push($data, [
                            'majorName'   =>$jobCard['majorName'] ?? '',
                            'deviceNum'   =>$device['deviceNum'] ?? '',
                            'deviceKind'  =>$jobCard['deviceKind'] ?? '',
                            'receiverName'=>$device['receiverName'] ?? '',
                            'completeTime'=>$device['completeTime'] ?? ''
                        ]);
                    }
                    break;
                case "日常维修单":
                    $result = Malfunction::getData(['receiverPeople'=>cookie('userId'), 'datetime'=>['like', $datetime.'.*']],false);  //故障报修单
                    foreach ($result as $malfunction) {
                        array_push($data, [
                            'majorName'   =>'',
                            'deviceNum'   =>'',
                            'deviceKind'  =>'',
                            'receiverName'=>$malfunction['people'],
                            'completeTime'=>$malfunction['datetime']
                        ]);
                    }
                    break;
            }
        }
        return RD(SUCCESS, $data);
    }

    /**
     * 获取报修单数
     * @param string $warrantyMaintenance  我的报修或已完成
     */
    public static function getOrderNum($warrantyMaintenance = '')
    {
        $warrantyMaintenance = input('warrantyMaintenance');

        $malCount = 0; $jobCount = 0;$inspectionCount = 0;
        if($warrantyMaintenance == '我的报修') {
            $malCount = count(Malfunction::getData(['people'=>cookie('userId'), 'datetime'=>['>=', date('Y')]], false)); //故障报修单
        }
        if($warrantyMaintenance == '已完成') {
            $malCount = count(Malfunction::getData(['receiverPeople'=>cookie('userId'), 'maintainDatetime'=>['>=', date('Y')]], false));  //故障报修单
            $jobCount = count(JobCard::getData(['receiverId'=>cookie('userId'),'completeTime'=>['>=', date('Y')]], false));
        }
        return RD(SUCCESS, ['维保作业单'=>$jobCount, '日常维修单'=>$malCount, '设备巡检'=>$inspectionCount]);
    }
    /**
     * 获取所有用户
     * @param string $keyword  搜索关键字
     * @return array
     */
    public static function getAllPeoples($keyword = null)
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;
        $keyword = input('keyword');
        $storeId = User::getStoreId();

        $data = self::getData(['username'=>['like', '.*'.$keyword.'.*'], 'store_id'=>$storeId], false);
        $returnData = [];
        foreach ($data as $key=>$user) {
            array_push($returnData, ['name'=>$user['username'], 'id'=>$user['id'], 'phone'=>$user['phone']]);
        }
        return RD(SUCCESS, $returnData);
    }

    /**获取审核通知
     * @param string $auditingState  审核状态  审核状态 （待审核、已通过、未通过）
     */
    public static function auditingNotices($auditingState = '', $currentPage = '', $pageSize = '')
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;

        $auditingState = input('auditingState');
        $currentPage   = input('currentPage');
        $pageSize      = input('pageSize');

        $data = [];
        $user = self::getData(['id'=>cookie('userId')]);
        $storeId = $user['store_id']??'';
        if(($user['rankName']??'') == '管理员' || ($user['rankName']??'') == '经理') {

            switch ($auditingState) {
                case '待审核':
                    $data = self::getData(['status'=>'待审核', 'store_id'=>['like', ".*".$storeId.'.*']], false);
                    break;
                case '已通过':
                    $data = self::getData(['status'=>'已通过', 'store_id'=>['like', ".*".$storeId.'.*']], false);
                    break;
                case '未通过':
                    $data = self::getData(['status'=>'未通过', 'store_id'=>['like', ".*".$storeId.'.*']], false);
                    break;
            }
        }
        $returnData = [];
        foreach ($data as $key=>$value) {
            array_push($returnData, [
                'id'      =>$value['id']??'',
                'userName'=>$value['username']??'',
                'phone'   =>$value['phone']??'',
                'store'   =>Store::getData(['id'=>$value['store_id']])['storeName'] ?? '',
                'dateTime'=>$value['datetime'] ?? '',
                'position'=>$value['rankName'] ?? '',
                'desc'    =>$value['desc'] ?? '',
                ]);
        }
        $count = count($returnData);
        if(!empty($pageSize) && !empty($currentPage))
            array_paging($returnData, ($currentPage - 1)* $pageSize, $pageSize);
        return RD(SUCCESS, ['total'=>$count, 'data'=>$returnData]);
    }

    /**
     * 操作审核通知
     * @param string $id
     * @param string $auditingState  审核状态  审核状态 （通过、拒绝、撤销）
     */
    public static function doAuditing($id = '', $auditingState = '')
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;
        $id            = input('id');
        $auditingState = input('auditingState');

        switch ($auditingState) {
            case '撤销':
                self::setData(['id'=>$id], ['status'=>'待审核']);
                break;
            case '通过':
                self::setData(['id'=>$id], ['status'=>'已通过']);
                break;
            case '拒绝':
                self::setData(['id'=>$id], ['status'=>'未通过']);
                break;
        }
        return RD(SUCCESS);
    }
    /**切换门店
     * @param string $id  门店id
     * @return array
     */
    public static function switchStores($id = '')
    {
        if(!empty($perssion = perssion([LOGIN])))   //权限判断
            return $perssion;

        $id = input('id');

        $rankName = User::getData(['id'=>cookie('userId')])['rankName'] ?? '';
        if($rankName == '管理员') {
            cache(cookie('userId').'storeId', NULL);         //清空缓存
            User::setData(['id'=>cookie('userId')], ['store_id'=>$id]);
        }
        return RD(SUCCESS);
    }
}